<?php

namespace app\service;

use think\exception\ValidateException;

class ImageService
{
    public function mergeMultipleImagesToBrowser($baseImageUrl, $overlayImageUrls, $positions)
    {
        // 下载底图
        $baseImage = $this->downloadImage($baseImageUrl);


        if (!$baseImage) {
            throw new ValidateException('Failed to download base image.');
        }
        $baseWidth = imagesx($baseImage);
        $baseHeight = imagesy($baseImage);
        $originalHeight = $baseHeight;
        $originalWidth = $baseWidth;
        //todo 合成一个白图
        $whiteMapHeight = 320; // 可以根据需要调整
        $newHeight = $originalHeight + $whiteMapHeight;
        $mergedImage = imagecreatetruecolor($originalWidth, $newHeight);

        // 创建一个白色的矩形（地图）
        $whiteMap = imagecreatetruecolor($originalWidth, $whiteMapHeight);
        $whiteColor = imagecolorallocate($whiteMap, 255, 255, 255); // 白色
        imagefill($whiteMap, 0, 0, $whiteColor);
        imagecopy($mergedImage, $baseImage, 0, 0, 0, 0, $originalWidth, $originalHeight);

        // 将白色地图复制到新画布的底部
        imagecopy($mergedImage, $whiteMap, 0, $originalHeight, 0, 0, $originalWidth, $whiteMapHeight);
        $newbaseWidth = imagesx($mergedImage);
        $newbaseHeight = imagesy($mergedImage);

        //再合成一次 button
        $buttonImagepath = './haibao.png'; // 使用 PNG 格式以支持透明度
        $buttonImage = imagecreatefrompng($buttonImagepath);
        if (!$buttonImage) {
            die('无法创建按钮');
        }

        $overbuttonWidth = imagesx($buttonImage);
        $overbuttonHeight = imagesy($buttonImage);
        if (!$buttonImage) {
            throw new ValidateException("Failed to download overlay image from {$buttonImage}.");
        }
        $destX = 0;
        $destY = $newbaseHeight - $overbuttonHeight;
        imagecopy($mergedImage, $buttonImage, $destX, $destY, 0, 0, $overbuttonWidth, $overbuttonHeight);
        // 释放内存
        //imagedestroy($overlayImage);



        // 遍历每个叠加图
        foreach ($overlayImageUrls as $index => $overlayImageUrl) {
            // 下载叠加图
            $overlayImage = $this->downloadImage($overlayImageUrl);
            if (!$overlayImage) {
                throw new ValidateException("Failed to download overlay image from {$overlayImageUrl}.");
            }
            $overlayWidth = imagesx($overlayImage);
            $overlayHeight = imagesy($overlayImage);

            // 获取叠加图的位置
            $position = $positions[$index] ?? 'top-left';
            //todo 缩放二维码
            if ($index == 1) {  //就是第二张就缩放下
//                // 获取原图的实际尺寸
                $scalePercentage = 60; // 80%
//                // 计算目标宽度和高度
                $targetWidth = ($overlayWidth * $scalePercentage) / 100;
                $targetHeight = ($overlayHeight * $scalePercentage) / 100;
                // 创建一个新的真色彩图像资源，大小与原图相同
                $finalImage = imagecreatetruecolor($overlayWidth, $overlayHeight);

                // 启用 alpha 通道（透明度）
                imagealphablending($finalImage, false);
                imagesavealpha($finalImage, true);
                // 设置背景颜色为透明
                $transparentColor = imagecolorallocatealpha($finalImage, 0, 0, 0, 127);
                imagefill($finalImage, 0, 0, $transparentColor);

                // 创建一个临时的缩放图像资源
                $thumbImage = imagecreatetruecolor($targetWidth, $targetHeight);
                // 启用 alpha 通道（透明度）
                imagealphablending($thumbImage, false);
                imagesavealpha($thumbImage, true);

                // 缩放并复制图片
                imagecopyresampled($thumbImage, $overlayImage, 0, 0, 0, 0, $targetWidth, $targetHeight, $overlayWidth, $overlayHeight);

// 将缩放后的图像复制到最终图像的中心位置
                $offsetX = ($overlayWidth - $targetWidth) / 2;
                $offsetY = ($overlayHeight - $targetHeight) / 2;
                imagecopy($finalImage, $thumbImage, $offsetX, $offsetY, 0, 0, $targetWidth, $targetHeight);
                $overlayImage = $finalImage;
            }


            // 计算叠加位置
            switch ($position) {
                case 'top-left':
                    $destX = 0;
                    $destY = 0;
                    break;
                case 'top-right':
                    $destX = $baseWidth - $overlayWidth;
                    $destY = 0;
                    break;
                case 'bottom-left':
                    $destX = 0;
                    $destY = $newbaseHeight - $overlayHeight;
                    //微调整
                    // -200 高度小了，就是往上定位了
                    // -50 小了，就是往左了
                    //宽度加50就是往右

                    $destY = $destY - 100;// 高度小了，就是往上定位了
                    //不考虑+-  而是考虑总值
                    $destX = $destX + 100;// 小了，就是往左了

                    break;
                case 'bottom-right':
                    $destX = $baseWidth - $overlayWidth;
                    $destY = $newbaseHeight - $overlayHeight;
                    $destY = $destY + 60;//  (80 比100 高一点)
                    $destX = $destX + 0;//
                    break;
                case 'center':
                    $destX = ($baseWidth - $overlayWidth) / 2;
                    $destY = ($newbaseHeight - $overlayHeight) / 2;
                    break;
                default:
                    $destX = 0;
                    $destY = 0;
                    break;
            }

            // 合并图像
            //imagecopy($baseImage, $overlayImage, $destX, $destY, 0, 0, $overlayWidth, $overlayHeight);
            imagecopy($mergedImage, $overlayImage, $destX, $destY, 0, 0, $overlayWidth, $overlayHeight);
            // 释放内存
            imagedestroy($overlayImage);
        }
        //在来一张 over


        // 直接输出到浏览器
        header('Content-Type: image/png');
        //imagepng($baseImage);
        imagepng($mergedImage);
        // 释放内存
        //imagedestroy($baseImage);
        imagedestroy($mergedImage);
    }

    function resizeImage($source, $dest, $newWidth, $newHeight)
    {
        $sourceImage = imagecreatefromjpeg($source);
        $resizedImage = imagecreatetruecolor($newWidth, $newHeight);

        imagecopyresampled($resizedImage, $sourceImage, 0, 0, 0, 0, $newWidth, $newHeight, imagesx($sourceImage), imagesy($sourceImage));

        imagejpeg($resizedImage, $dest);

        imagedestroy($sourceImage);
        imagedestroy($resizedImage);
    }

    // 图片裁剪
    function cropImage($source, $dest, $newWidth, $newHeight, $x, $y)
    {
        $sourceImage = imagecreatefromjpeg($source);
        $croppedImage = imagecrop($sourceImage, ['x' => $x, 'y' => $y, 'width' => $newWidth, 'height' => $newHeight]);

        imagejpeg($croppedImage, $dest);

        imagedestroy($sourceImage);
        imagedestroy($croppedImage);
    }

    //https://www.yisu.com/ask/2450839.html


    private function downloadImage($imageUrl)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $imageUrl);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        //if https
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

        $imageData = curl_exec($ch);
        curl_close($ch);

        if ($imageData === false) {
            echo 1;
            return null;
        }

        $image = imagecreatefromstring($imageData);
        if (!$image) {
            echo 2;
            return null;
        }

        return $image;
    }
}